<template>
  <!-- ref属性是vue提供来定位元素使用的 -->
  <el-form :model="user" :rules="userRules" ref="loginForm" class="login-form">
    <el-form-item>
      <span style="width:100%;font-weight: bold;font-size: 30px;margin-left: 100px">电力巡检系统</span>
    </el-form-item>
    <!-- form表单的校验规则中的属性必须与这个form表单项的prop属性值保持一致   -->
    <el-form-item prop="username">
      <el-input v-model="user.username" placeholder="请输入账号" prefix-icon="el-icon-user" clearable/>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="user.password" type="password" placeholder="请输入密码" prefix-icon="el-icon-lock" show-password clearable />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="login()" style="width: 100%;">登陆</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  name: "Login",
  data(){
    return {
      user: {
        username: '',
        password: ''
      },
      userRules: {
        //username的校验规则
        username: [
          {required: true, message: '账号不能为空', trigger: ['blur', 'change']}
        ],
        //password的校验规则
        password: [
          {required: true, message: '密码不能为空', trigger: ['blur', 'change']}
        ]
      }
    }
  },
  methods: {
    login(){
      //$refs是vue提供来定位元素的，需要与元素的ref属性配合使用
      //validate()函数是el-form的验证函数
      this.$refs['loginForm'].validate((valid) => {
        if(valid){
          //如果校验成功，那么我们就可以将用户的信息发送到后端服务器进行登录操作
          this.doPost('/login', this.user, resp => {
            if(resp === 1){//登陆成功
              this.$router.push({name: 'Manage'}) //页面跳转
            } else if(resp === 0){
              this.$message.error("账号或密码错误")
            } else if(resp === -1){
              this.$message.error("账号不存在，请联系管理员")
            } else {
              this.$message.error("账号被冻结，请联系管理员")
            }
          })
        } else {
          return false
        }
      })
    },
    gotoRegister(){
      this.$router.push({name: 'Register'})
      // this.$router.push({path: '/register'})
    }
  }
}
</script>

<style scoped>
.login-form {
  background-image: url("../assets/bg.jpg");
  width: 400px;
  box-shadow: 1px 1px 6px 2px #a39d9d;
  border-radius: 5px;
  margin: 15% auto;
  padding: 40px 30px;
}
</style>
